
<!DOCTYPE html> 
<html lang="zh-cn"> 
<head> 
	<title>后台管理</title> 
	<meta charset='utf-8' />
	<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
	<style>
		/*div{border:1px solid;}*/

		*{box-sizing:border-box}
		#fpage a{
			cursor:pointer;
		}
	</style>
</head> 
<body style='background:#ccc'> 
	<!--退出登陆-->
	<div style='text-align:right;padding:10px;color:blue'><span style='cursor:pointer' id='exit'>退出</span></div>

	<!--顶排-->
	<h1 style='text-align:center'>UpYun后台管理</h1>

	<div style='display:flex'>
		<div style='flex:1'>
			<button id='CreateDirBtn' class='AddArea'>创建目录</button>
			<div id='CreateDirArea' style='display:none'  class='AddArea'>
				<input id='CreateDirInp' style='width:100px' placeholder='目录名' />
				<button id='CreateDirSub'>提交</button>
				<button id='CreateDirBack'>返回</button>
			</div>
			<button id='AddFileBtn'  class='AddArea'>上传文件</button>
			<div id='AddFileArea' style='display:none'  class='AddArea'>
				<input id='AddFileInp' type='file' style='width:60px' />
				<span><img src='' id='AddFileImg' style='width:100px;display:none'/></span>
				<button id='AddFileSub'>提交</button>
				<button id='AddFileBack'>返回</button>
			</div>
		</div>

		<div style='text-align:right;flex:1'>
			服务选择：
			<select id='service_list'>
				<option value=''>暂无服务</option>
			</select>

			<button id="del_service">删除服务</button>
			<button id="add_service_init">添加服务</button>
			<span id='add_service_area' style='display:none'>
				<div>
					<input type="text" name='add_service_inp' placeholder='服务名' />
					<input type="text" name='add_service_inp2' placeholder='域名:http://...' />
					<button type='button' id='add_service_but' >添加</button>
					<button type='button' id='add_service_back' >返回</button>
				</div>
			</span>
		</div>
	</div>


	<hr>



	<div style='padding:5px 20px;'>
		当前目录：
		<span style='color:blue' id='CurrentPath'>/aa/bb/cc</span>　
		<button id='JumpBack'>返回上层</button>
		<div style='float:right'>
			<button id='refresh'>刷新当前</button>
			<button id='refresh2'>刷新全部</button>
		</div>
	</div>		<!--当前路径-->

	<div style='padding:5px 20px'>						<!--内容显示区-->
		<div style='color:green' id='DirArea'>
			<!--目录：<span>目录1</span>　
			<span><button>删除</button></span-->
		</div>
		<div id='PagesArea'>
			<!--文件：<span>http://www.baid.com/aa/bb/cc/sdf.jpg</span>　
			<span><button>删除</button></span-->
		</div>
		<div id='CheckAllArea' style='display:none;margin:10px auto;;padding:10px 0;border-top:1px solid #aaa'>
			<label><input type="checkbox" id='CheckAllInp' />全选/全不选</label>　
			<button id='CheckTrans'>反选</button>　
			<button id='DeleteAll'>删除选中</button>
		</div>
	</div><!--二排内容区结束-->


	<div id='Notice'></div>


</body> 
</html>

<script src="./Include/jquery.js"></script> 
<script src="./Include/md5.js"></script> 
<script>

	//判断登陆用户
	setInterval(function(){
		if(!sessionStorage.login){
			location.replace('login.html');
		}
	},500);

	var url = 'interface.php';
	var folders = [];                   //目录容器
	var pages = [];                     //文件容器
	sessionStorage.dir_currnet = '/';   //当前目录
	sessionStorage.dir_arr = '["/"]'; 	//历史目录容器
	var file = '';
	var img_rand='';                    //刷新时作用于图片


	//退出
	$('#exit').click(function(){
		sessionStorage.login = '';
		location.reload();exit;
	});


	//全选
	$('#CheckAllInp').change(function(){
		if($('#CheckAllInp').is(':checked')){
			var stat = true;
		}else{
			var stat = false;
		}
		$('.DelBox').each(function(i,o){
			o.checked = stat;
		});
	});

	//返选
	$('#CheckTrans').click(function(){
		$('.DelBox').each(function(i,o){
			o.checked = !o.checked;
		});
	});


	//多选删除
	$('#DeleteAll').click(function(){
		if(!confirm('确认删除选中？')){
			return;
		}
		var arr = [];
		$('.DelBox').each(function(i,o){
			if(o.checked){
				arr.push(o.value);
			}
		});
		if(arr.length < 1){
			return;
		}
		Notice('处理中......');
		var str = arr.join(',');
		var data = {
			type:'DeleteMulti',
			paths:str,
			service:GetSevice(1),
			cache_path:GetCurrentDirCache()
		}
		Ajax2(data,function(res){
			if(res == 'ok'){
				Notice();
				A('操作成功！');
				GetDirContent(); //四：从upyun或sess获取指定目录内容
			}
		},url);
	});


	//刷新
	$('#refresh,#refresh2').click(function(){
		if(!confirm('确认该操作？')){
			return;
		}
		var path = GetCurrentDirCache();
		var data = {
			path:path,
			type:'refresh',
			refresh_type:$(this).attr('id')
		}
		Ajax2(data,function(res){
			img_rand = '?a='+Math.random();	//图片随机尾
			GetDirContent();
		},url);
	});

	//选择图片并显示 
	SelectOrViewImg('AddFileInp','AddFileImg',function(f){
		var ext = f.name.substring(f.name.lastIndexOf('.')+1);
		switch(ext){
			case 'jpg':case 'jpeg':case 'png':case 'gif':case 'bmp':
			case 'JPG':case 'JPEG':case 'PNG':case 'GIF':case 'BMP':
				$('#AddFileImg').show();
			break;
			default:
				$('#AddFileInp').width('100px');
			break;
		}
		file = f;
	});

	//上传文件提交
	$('#AddFileSub').click(function(){
		if(!file){
			return;
		}
		Notice('处理中......');
		var type = 'upload_img';
		Ajax({'type':'token','token_name':type},function(t){
			var fd = new FormData();
			fd.append('type',type);
			fd.append('token',t);
			fd.append('file',file);
			fd.append('service',GetSevice(1));
			fd.append('path',GetCurrentPath());
			fd.append('cache_path',GetCurrentDirCache());
		    $.ajax({
		        url:url,
		        type: 'POST',
		        data:fd,
		        processData: false,
		        contentType: false,
		        success : function(res) {

					Notice();
		        //	C(res);
		           	if(res == 'ok'){
		           		A('文件上传成功！');
						file = '';
						//$('#CreateDirBack,#AddFileBack').trigger('click');
						$('#AddFileImg').hide();
		           		GetDirContent();
		           	}else{
		           		A('文件已存在或上传异常！');
		           	}
		        }
		    });
		},url);
	});


	//点击 创建目录 或 上传文件
	$('#CreateDirBtn,#AddFileBtn').click(function(){
		$('.AddArea').hide();
		if($(this).attr('id') == 'CreateDirBtn'){
			$('#CreateDirArea').show();
		}else{
			$('#AddFileArea').show();
		}

	});
	//返回按钮
	$('#CreateDirBack,#AddFileBack').click(function(){
		$('.AddArea').hide();
		$('#CreateDirBtn').show();
		$('#AddFileBtn').show();
		$('#AddFileInp').width('60px');
		$('#AddFileImg').attr('src','').hide();
		file = '';
	});


	//创建目录提交
	$('#CreateDirSub').click(function(){
		var name = $('#CreateDirInp').val().trim();
		if(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(name)){
		}else{
			A('目录名非法！');return;
		}
		Notice('处理中......');
		var path = GetCurrentPath();
		if(path == '/'){
			var full_path = path + name;
		}else{
			var full_path = path +'/'+ name;
		}
		var cache_path = GetCurrentDirCache();
		var data = {
			type:'CreateDir',
			path:full_path,
			cache_path:cache_path,
			service:GetSevice(1)
		}
		Ajax2(data,function(res){
			Notice();
			if(res == 'ok'){
				A('创建成功！');
				$('#CreateDirInp').val('');
				$('.AddArea').hide();
				$('#CreateDirBtn').show();
				$('#AddFileBtn').show();
				GetDirContent();
			}else{
				A('创建失败！');
			}
		},url);
	});






	//获取当前目录的缓存路径
	function GetCurrentDirCache(){
		return 'Cache/'+md5(GetSevice(1)+sessionStorage.dir_currnet)+'.html';
	}



	//获取当前服务名或域名，传值获取服务名，默认获取服务域名
	function GetSevice(type){
		if(type){
			return $('#service_list').find('option:selected').text();
		}else{
			return $('#service_list').find('option:selected').val();
		}
	}


	//获取当前文件或目录的路径
	function GetCurrentPath(name){
		if(name){
			if(sessionStorage.dir_currnet == '/'){
				var tmp_path = '/'+name;
			}else{
				var tmp_path = sessionStorage.dir_currnet+'/'+name;
			}
		}else{
			var tmp_path = sessionStorage.dir_currnet;
		}
		return tmp_path;
	}


	//服务切换
	$('#service_list').change(function(){
		sessionStorage.service_current_index = $('#service_list').find('option:selected').index();
		sessionStorage.dir_currnet = '/';   //当前目录
		sessionStorage.dir_arr = '["/"]'; 	//历史目录容器
		GetDirContent(); //四：从upyun或sess获取指定目录内容
	});



	//一：获取服务列表,并解析
	GetServiceList();
	function GetServiceList(){
		if(sessionStorage.GetServiceList){
			//C('sess');
			ParseServiceList(sessionStorage.GetServiceList);
		}else{
			Ajax2({type:'GetServiceList'},function(res){
				//C('after');
				sessionStorage.GetServiceList = res;
				ParseServiceList(res);
			},url);
		}
	}




	//二：解析服务列表
	function ParseServiceList(res){
		if(/^\[{"name":.*\}]$/.test(res)){
			var list = JSON.parse(res);
			var list_str = '';
			for(var i=0;i<list.length;i++){
				list_str += "<option value='"+decodeURIComponent(list[i].url)+"'>"+list[i].name+"</option>";
			}
			$('#service_list').html(list_str);
		}else{
			$('#service_list').html("<option>暂无服务</option>");
		}

		GetDirContent(); //四：从upyun或sess获取指定目录内容
	}





	//四：从upyun或sess获取指定目录内容
	function GetDirContent(){

		if(sessionStorage.service_current_index){
			service_list.options[sessionStorage.service_current_index].selected = true;
		}
		folders = [];
		pages = [];
		$('#PagesArea').html('');
		$('#DirArea').html('');
		var path = sessionStorage.dir_currnet;
		if(path == '/'){
			$('#JumpBack').hide();
		}else{
			$('#JumpBack').show();
		}
		$('#CurrentPath').text(path);
		if(!path){return;}
		var service = GetSevice(1);
		var cache = 'Cache/'+md5(service+path)+'.html';
		Ajax({},function(res){
			if(/^{.*}$/.test(res)){
				C('cache');
				ParseDir(res);
			}else{
				var data = {
					type:'GetDirContent',
					path:path,
					service:service
				}
				Ajax2(data,function(res2){
					C('after');
					ParseDir(res2);
				},url);
			}
		},cache);
	}





	//五：解析目录内容
	function ParseDir(res){
		if(!/^{.*}$/.test(res)){
			return;
		}
		var data = JSON.parse(res);
		var files = data.files;
		if(files.length < 1){
			$('#CheckAllArea').hide();	//隐藏多选删除区
			return;
		}
		$('#CheckAllArea').show();		//显示多选删除区
		
		//将页面和目录分类装载
		for(var i=0;i<files.length;i++){
			if(files[i].type == 'N'){
				pages.push(files[i]);
			}else{
				folders.push(files[i]);
			}
		}
		LoadDirData();	//加载目录数据
		LoadPagesData();	//加载文件数据
	}


	//加载目录数据
	function LoadDirData(){
		if(folders.length > 0){
			var f_str = '';
			for(var i=0;i<folders.length;i++){
				var tmp_path = GetCurrentPath(folders[i].name);
				f_str += "<div><label><input type='checkbox' class='DelBox' value='"+tmp_path+"' />目录：</label><span onclick='JumpDir(this)'>"+folders[i].name+"</span>　<span style='margin-left:50px'><button onclick=DelFileDir('"+tmp_path+"')>删除</button></span><div>";
			}
			$('#DirArea').html(f_str);
		}else{
			$('#DirArea').html('');
		}
	}



	//加载文件数据
	function LoadPagesData(){
		if(pages.length > 0){
			var f_str = '';
			var domain = GetSevice();
			if(sessionStorage.dir_currnet == '/'){
				var url = domain+'/';
			}else{
				var url = domain+sessionStorage.dir_currnet+'/';
			}

			for(var i=0;i<pages.length;i++){
				var size = '大小：'+Math.ceil(pages[i].size/1024)+' KB';
				var ext = pages[i].name.substring(pages[i].name.lastIndexOf('.')+1);
				var tmp_path = GetCurrentPath(pages[i].name);	//获取当前文件或目录的路径
				switch(ext){
					case 'jpg':case 'jpeg':case 'gif':case 'png':case 'bmp':
					case 'JPG':case 'JPEG':case 'GIF':case 'PNG':case 'BMP':
						var img_tmp = url+pages[i].name+img_rand;
						f_str += "<div><label><input type='checkbox' class='DelBox' value='"+tmp_path+"' />图片：</label><img src='"+img_tmp+"' style='height:60px' class='cat_img' />　<span>"+pages[i].name+"</span>　<span>"+size+"</span>　<span style='margin-left:50px'><button onclick=DelFileDir('"+tmp_path+"')>删除</button></span><div>";
						break;
					default:
						var tmp_url = url+pages[i].name;
						var img_tmp = 'http://upyun.bm123.top/PublicImage/base.png';
						f_str += "<div><label><input type='checkbox' class='DelBox' value='"+tmp_path+"' />文件：</label><img src='"+img_tmp+"' style='height:60px' class='cat_img' />　<a href='"+tmp_url+"' target='_blank'><span>"+pages[i].name+"</span></a>　<span>"+size+"</span>　<span style='margin-left:50px'><button onclick=DelFileDir('"+tmp_path+"')>删除</button></span><div>";
						//var tmp_url = url+pages[i].name;
						//f_str += "<div><label><input type='checkbox' class='DelBox' value='"+tmp_path+"' />文件：</label><a href='"+tmp_url+"' target='_blank'><span>"+pages[i].name+"</span></a>　<span><button onclick=DelFileDir('"+tmp_path+"')>删除</button></span><div>";
						break;
				}
			}
			$('#PagesArea').html(f_str);
		}else{
			$('#PagesArea').html('');
		}


		$('.cat_img').click(function(){
			if(sessionStorage.cat_img){
				sessionStorage.cat_img = '';
				$(this).height('60px');
			}else{
				sessionStorage.cat_img = 1;
				$(this).height('400px');
			}
		}).mouseout(function(){
			$(this).height('60px');
			sessionStorage.cat_img = '';
		});
	}


	//删除文件或目录
	function DelFileDir(path){
		if(!confirm('确认删除?')){
			return;
		}
		Notice('处理中......');
		var cache_path = GetCurrentDirCache();	//获取当前目录的缓存路径
		var data = {
			type:'DelFileDir',
			path:path,
			service:GetSevice(1),
			cache_path:cache_path
		}
		Ajax2(data,function(res){
			Notice();
			if(res == 'ok'){
				A('删除成功！');
				GetDirContent(); //四：从upyun或sess获取指定目录内容
			}else{
				A('删除失败！');
			}
		},url);
	}


	//跳转到下级目录
	function JumpDir(o){
		var dir_name = $(o).text();
		if(sessionStorage.dir_currnet == '/'){
			var new_dir = sessionStorage.dir_currnet+dir_name;
		}else{
			var new_dir = sessionStorage.dir_currnet+'/'+dir_name;				
			var arr = JSON.parse(sessionStorage.dir_arr);
			arr.push(sessionStorage.dir_currnet);
			sessionStorage.dir_arr = JSON.stringify(arr);
		}
		sessionStorage.dir_currnet = new_dir;
		GetDirContent(); //四：从upyun或sess获取指定目录内容
	}

	JumpBack.onclick=function(){
		var dir_arr = JSON.parse(sessionStorage.dir_arr);
		if(dir_arr.length > 1){
			var last = dir_arr.pop();
			sessionStorage.dir_arr = JSON.stringify(dir_arr);
		}else{
			var last = '/';
		}
		sessionStorage.dir_currnet = last;
		GetDirContent(); //四：从upyun或sess获取指定目录内容
	}









	//触发添加服务
	$("#add_service_init").click(function(){
		$(this).hide();
		$("#add_service_area").show();
	});

	$('#add_service_back').click(function(){
		$("#add_service_init").show();
		$("#add_service_area").hide();
	});

	//服务添加事件
	$("#add_service_but").click(function(){
		var service_name = $("input[name=add_service_inp]").val().trim();
		var service_url = encodeURIComponent($("input[name=add_service_inp2]").val().trim());
		if(!service_name || !service_url){
			C('缺少参数！');return;
		}
		var data = {
			type:'add_service',
			service_name:service_name,
			service_url:service_url
		}
		Ajax2(data,function(res){
			switch(res){
				case 'err1':
					A('缺少参数！');break
				case 'err2':
					A('服务已存在！');break
				case 'err3':
					A('请重新添加！');break
				case 'ok':
					A('操作成功！');
					$("input[name=add_service_inp]").val('');
					$("input[name=add_service_inp2]").val('');
					sessionStorage.GetServiceList = '';
					GetServiceList();
					$('#add_service_back').trigger('click');
					break
			}
		},url);
	});



	//服务删除 
	$("#del_service").click(function(){
		if(!confirm('确认该操作吗?')){
			return;
		}
		var data = {
			type:'del_service',
			name:$('#service_list').find('option:selected').text().trim()
		}
		Ajax2(data,function(res){
			if(res == 'ok'){
				A('操作成功！');
				sessionStorage.GetServiceList = '';
				GetServiceList();
			}else{
				A('操作异常！');
			}
		},url);
	});






function C(r){
	console.log(r);
}
function A(r){
	alert(r);
}







function Ajax2(data,fun,url){
	GetToken(data.type,url,function(t){
		data.token = t;
		data.token_name = data.type;
		Ajax(data,function(res){
			fun(res);
		},url);
	});
}
function GetToken(token_name,url,fun){
	var data = {
		type:'token',
		token_name:token_name
	}
	Ajax(data,function(t){
		fun(t);
	},url);
}
/*
	###   ajax 异步加载 (JQUERY方式)
	参一：要传送的数据
	参二：成功回调
	参三：请求的后台地址
	参四：是否异步.当无值时默认为异步，当有值时为同步
	参五：提交方式 默认为post,有值为get
	示例：
		var data = {
					token:t,
					type:type,
					openid:openid
				};

		 Ajax(data,function(res){
		 	alert(res);
		 });
		 或
		 },1);
*/
function Ajax(data,fun,url,async,stat){
	if(!stat){
		stat = 'post';
	}else{
		stat = 'get';
	}
	async = async?false:true;
	if(!url){
		url = 'interface.php';
	}
	$.ajax({
		url:url,
		type:stat,
		async:async,
		data:data,
		success(rq_res,rq_stat,rq_xhr){
			fun(rq_res,rq_stat,rq_xhr);
		},
		error(){
			fun('false');
		}
	});
}



/*
	### 表单选择并读取文件，如是图片并显示
	参一：文件选择表单项的id
	参二：要显示图片的元素id,如果为空则不显示图片
	参三：回调(返回file或'err')
	示例：
		<input type='file' id='a' />
		<img src='' id='b' />
		SelectOrViewImg('a','b',function(f){
			alert(f);
		});
*/
function SelectOrViewImg(file_input_id,view_id,fun){
	var StoreMain_File = document.getElementById(file_input_id);
	var view_ele = document.getElementById(view_id);
	StoreMain_File.onchange=function(){
		var file = StoreMain_File.files[0];
		var reader = new FileReader();
		reader.onloadend = function(){
			if(view_id){	//如果指定了图片显示元素，则显示图片
				view_ele.src = reader.result;
			}
		}
		if(file){
			reader.readAsDataURL(file);
			fun(file);
		}else{
			fun('err');
		}
	};
}



/*
	### 蒙板提示框(提示时页面被盖不可操作)
	### 参一：提示内容
	### 需要：函数需要一个 id='notice' 的元素做容器
	### 示例：
		 <div id='Notice'></div>
		 Notice('信息发布成功！'); //开启提示框
		 Notice();	//关闭提示框
*/
function Notice(text){
	if(text){
		var str = "<div style='z-index:100;position:fixed;top:0px;width:100%;height:100%;background:rgba(255,100,100,0.5)'><div id='notice_text' style='background:#fff;width:200px;margin:20% auto;text-align:center;padding:30px;border-radius:10px'>"+text+"</div></div>";
		$('#Notice').html(str);
	}else{
		$("#Notice").html('');		
	}
}



</script> 

		







